var express = require("express");
var app = express();
const { connection } = require("./db");

//静态文件托管
// app.use(express.static('./dist'))

//解决跨域
app.use(require("cors")());

//解析json 用于解析post方法 req.body中的数据
app.use(express.json());

const resStatus = {
  code: 200,
  data: [],
  msg: "success",
  total: 0,
};

//新建文章
app.post("/api/articles", async (req, res) => {
  console.log(req.body, "新建文章");
  const query = `INSERT INTO article (title, content) VALUES ('${req.body.title}', '${req.body.content}')`;
  connection.query(query, (error, results) => {
    if (error) {
      console.error("Error in query: ", error);
      res.send(error);
    } else {
      console.log("Data added successfully!");
      res.send(resStatus);
    }
  });
});
//文章列表
app.get("/api/articles", async (req, res) => {
  console.log(req.query, "查询字符");
  let total = 0;
  let pageNo = req.query.currentPage;
  let pageSize = req.query.pageSize;
  
  connection.query("SELECT COUNT(*) FROM article", function (err, results) {
    console.log(results[0]["COUNT(*)"], "total"); // results contains rows returned by server
    total = results[0]["COUNT(*)"];
    // DESC 降序 ASC 升序
    connection.query(
      `SELECT * FROM article WHERE title like '${req.query.title||"%"}' ORDER BY id DESC LIMIT ${(pageNo - 1) * pageSize}, ${pageSize}`,
      function (err, results, fields) {
        console.log(results); // results contains rows returned by server
        console.log(fields); // fields contains extra meta data about results, if available
        resStatus.data = results;
        resStatus.total = total;
        res.send(resStatus);
      }
    );
  });
});

//删除文章
app.delete("/api/articles/:id", async (req, res) => {
  const query = `DELETE from article WHERE id=${req.params.id}`;
  connection.query(query, (error, results) => {
    if (error) {
      res.send(error);
    } else {
      res.send(resStatus);
    }
  });
});
//修改文章
app.put("/api/articles", async (req, res) => {
  const query = `UPDATE article SET title='${req.body.title}',content='${req.body.content}'  WHERE id=${req.body.id}`;
  connection.query(query, (error, results) => {
    if (error) {
      res.send(error);
    } else {
      res.send(resStatus);
    }
  });
});
//文章详情
app.get("/api/articles/:id", async (req, res) => {
  const query = `SELECT * from article WHERE id=${req.params.id}`;
  connection.query(query, (error, results) => {
    if (error) {
      res.send(error);
    } else {
      resStatus.data = results;
      res.send(resStatus);
    }
  });
});

//监听服务端口
var server = app.listen(3000, () => {
  console.log("服务已开启，访问地址：localhost:3000");
});
